﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Jemgine.MapEditor
{
	public partial class EditorState
	{
        internal static TreeNode BuildElementNode(Data.MapElement Element, int TopIndex)
        {
            String Name = null;
            if (Element is Data.ScriptNode)
            {
                var Node = Element as Data.ScriptNode;
                Name = Node.Name;
            }
            if (String.IsNullOrEmpty(Name)) Name = Element.GetType().Name;
            
            TreeNode NewNode = new TreeNode(Name);
            NewNode.Tag = new Engine.Selection(Element.SelectionType(), TopIndex, 0, 0);

            if (Element is Data.EntityRecord)
            {
                Data.EntityRecord Entity = Element as Data.EntityRecord;
                
                for (int MiddleIndex = 0; MiddleIndex < Entity.AttachedElements.Count; ++MiddleIndex)
                {
                    Data.EntityElement EntityElement = Entity.AttachedElements[MiddleIndex];
                    TreeNode NewElementNode = new TreeNode(EntityElement.GetType().Name);
                    NewElementNode.Tag = new Engine.Selection(EntityElement.SelectionType(), TopIndex, MiddleIndex, 0);
                    NewNode.Nodes.Add(NewElementNode);
                }
            }

            return NewNode;
        }

        internal void RebuildNode(int TopIndex)
        {
            bool NodeExpanded = Tree[TopIndex].IsExpanded;
            Tree.RemoveAt(TopIndex);
            Tree.Insert(TopIndex, BuildElementNode(Map.Elements[TopIndex], TopIndex));
            if (NodeExpanded) Tree[TopIndex].Expand();
            TreeChanged();
        }

        internal void AddNewMapElementToTree(Data.MapElement Element, int TopIndex)
        {
            Tree.Insert(TopIndex, BuildElementNode(Element, TopIndex));
            TreeChanged();
        }

        internal void RemoveMapElementFromTree(int TopIndex)
        {
            Tree.RemoveAt(TopIndex);
            TreeChanged();
        }

        internal void _RebuildTree()
        {
            Tree.Clear();

            for (int TopIndex = 0; TopIndex < Map.Elements.Count; ++TopIndex)
                Tree.Add(BuildElementNode(Map.Elements[TopIndex], TopIndex));

            TreeChanged();
        }
	}
}
